package com.ymt.bpm.web.rest.platform;

import com.alibaba.fastjson.JSONObject;
import com.ymt.bpm.service.mobile.MAuthService;
import com.ymt.bpm.util.CaptchaUtil;
import com.ymt.bpm.util.Const;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping("/openapi/v1/auth")
public class AuthResource {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MAuthService mas;

    @PostMapping(path = "/login", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public JSONObject login(HttpServletRequest request,
                            HttpServletResponse response,
                            @RequestParam("j_username")String j_username,
                            @RequestParam("j_password")String j_password,
                            @RequestParam("time")Long time,
                            @RequestParam("captcha")String captcha
                            ) {
//        String login = map.get("j_username");
//        String password = map.get("j_password");
//        String time = map.get("time");
//        String captcha = map.get("captcha");
        String sessionCaptcha = (String)request.getSession().getAttribute(Const.CAPTCHA);
        if (log.isTraceEnabled()) {
            log.trace("login attemption on desktop j_username: "+ j_username);
            log.trace("login attemption on desktop time: "+ time);
            log.trace("login attemption on desktop captcha: "+ captcha);
            log.trace("login attemption on desktop session captcha: "+ sessionCaptcha);
        }
        JSONObject rtn = null;
        //check captcha
        String skipCaptcha = request.getParameter("skipCaptcha");   //for benchmark testing
        if (!"1".equalsIgnoreCase(skipCaptcha)) {
            if (captcha==null || (captcha!=null && !captcha.toLowerCase().equals(sessionCaptcha))) {
                rtn = new JSONObject();
                rtn.put(Const.AJAX_RESULT, 0);
                rtn.put(Const.AJAX_MSG, "WRONG_CAPTCHA");
                return rtn;
            }
        }

        //do login
        rtn = mas.login(j_username, j_password==null ? "" : j_password, time, mas.getExpires());
        //remove all cookies
        Cookie[] cookies = request.getCookies();
        if (cookies!=null) {
            for (Cookie c : cookies) {
                c.setMaxAge(0);
                c.setValue(null);
            }
        }
        //set new cookie
        String jwtToken = rtn.getString(Const.JWT_TOKEN);
        Cookie cookie = new Cookie(Const.JWT_TOKEN, jwtToken);
        cookie.setHttpOnly(true);   //防XSS
        cookie.setPath("/");
        response.addCookie(cookie);
        return rtn;
    }

    @GetMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        //生成随机字串
        String captcha = CaptchaUtil.generateVerifyCode(4);
        request.getSession().removeAttribute(Const.CAPTCHA);
        request.getSession().setAttribute(Const.CAPTCHA, captcha.toLowerCase());

        //生成图片
        int w = 100, h = 30;
        try {
            CaptchaUtil.outputImage(w, h, response.getOutputStream(), captcha);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
